import React, { useState, useEffect, useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import TopStatistic from './TopStatistic';
import SecondStatistic from './SecondStatistic';
import SecondCost from './SecondCost';
import ThirdSend from './ThirdSend';
import ThirdCallOut from './ThirdCallOut';
import ThirdCost from './ThirdCost';
import FourthBureau from './FourthBureau';
import type { IAuth } from './constant';
import './index.scss';

const HomePage: React.FC = () => {
  const history = useHistory();

  const [smsAuth, setSmsAuth] = useState({ data: 0, target: 0, call: 0 }); // 当前权限
  const [authCount, setAuthCount] = useState(0); // 权限计数

  const getAuth = useCallback(() => {
    try {
      const authData: IAuth = JSON.parse(sessionStorage.getItem('smsAuth'));
      // 有2就加一次，算有几个2
      const countNum: number = Object.values(authData).reduce(
        (prev, current) => (current === 2 ? prev + 1 : prev),
        0
      );

      if (countNum === 0) {
        history.push(`/401/noSmsAuth?state=0`);
        return;
      }
      setSmsAuth(authData);
      setAuthCount(countNum);
    } catch {
      history.push(`/401/noSmsAuth?state=0`);
    }
  }, [history]);

  useEffect(() => {
    getAuth();
  }, [getAuth]);

  return (
    <div className="page-main-container">
      <TopStatistic smsAuth={smsAuth} authCount={authCount} />

      <div className="row-wrapper">
        <SecondStatistic />
        <SecondCost />
      </div>

      <div className="row-wrapper">
        <ThirdSend />
        <ThirdCallOut />
        <ThirdCost />
      </div>

      <FourthBureau />
    </div>
  );
};

export default HomePage;
